<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #menu="{ model, field }">
        <BasicTree
          v-if="treeData.length>0"
          v-model:value="model[field]"
          :treeData="treeData"
          :fieldNames="{ title: 'menuName', key: 'id' }"
          checkable
          checkStrictly
          :auto-expand-parent="autoExpandParent"
          defaultExpandAll
          toolbar
          title="菜单分配"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { formSchema } from './role.data';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { BasicTree, TreeItem } from '@/components/Tree';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useI18n } from '@/hooks/web/useI18n';
  import {UpdateRole,AddRole} from '@/api/system/role';
  import { getRoleAllMenu } from '@/api/system/menu';
  const { notification } = useMessage();
  const { t } = useI18n();
  export default defineComponent({
    name: 'RoleDrawer',
    components: { BasicDrawer, BasicForm, BasicTree },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const treeData = ref<TreeItem[]>([]);
      var update = ''
      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        await resetFields();
        setDrawerProps({ confirmLoading: false });
        // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
        if (unref(treeData).length === 0) {
          const treeapidata = await getRoleAllMenu();
          let menu_data = treeapidata.data;
          menu_data = await convertKey(menu_data)
          treeData.value = (menu_data) as any as TreeItem[];
        }
        isUpdate.value = !!data?.isUpdate;
        update = data.record
        if (unref(isUpdate)) {
          await setFieldsValue({
            ...data.record,
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          // TODO custom api
          var menus_data:Array<any> = []
          console.log(values.menu)
            if(Array.isArray(values.menu) && values.menu != undefined && values.menu.checked == undefined){
              values.menu.forEach(element => {
                menus_data.push(element)
              })
              values.menuIds  = menus_data
            }else{
              values.menuIds  = values.menu?.checked
            }
            values.name  = values.roleName
            values['state'] = values['status']
          if (unref(isUpdate)) {
             values['id'] = update['id']
             const update_menu = await UpdateRole(values)
             if(update_menu.code == 200){
                notification.success({
                message: t('sys.update.success'),
                description: t('sys.update.success'),
                duration: 3,
              });
                closeDrawer();
                emit('success');
             }else{
                notification.error({
                message: t('sys.update.error'),
                description: update_menu.msg,
                duration: 3,
              });
             }
          }else{
            // add data
            const update_role = await AddRole(values)
             if(update_role.code == 200){
                notification.success({
                message: t('sys.add.addsuccess'),
                description: t('sys.add.addsuccess'),
                duration: 3,
              });
                closeDrawer();
                emit('success');
             }else{
                notification.error({
                message: t('sys.add.addfail'),
                description: update_role.msg,
                duration: 3,
              });
             }
          }
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }
      async function convertKey(menulist) {
          if (!menulist) return null;
          for (const map of menulist) {
            map['title'] = map.menuName
            map['key'] = map.id
            map['icon'] = map.icon
            if (map.children != undefined && map.children.length > 0) {
                var childrenList =await convertKey(map.children);
                map["children"]= childrenList;
            }
        }
        return menulist
      }
      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        treeData,
        convertKey
      };
    },
  });
</script>
